#!/bin/bash -e

# do not need mat_task number anymore, when exceed the number, it will goes wrong, then it wait, and submit again.

function info() {
echo Usage: `basename $0` [pmdnt] cmd args
exit 2
}

while getopts  ":p:t:m:d:n:" opt; do
	case $opt in
	p) cpu=$OPTARG;;
	m) mem=$OPTARG;;
	t) ids=$OPTARG;;
	d) job_id=$OPTARG;;
	n) name=$OPTARG;;
	?) info;;
	esac
done
shift $(($OPTIND - 1))

# echo $@

if [ $# -lt 1 ]; then info; fi

# . $var

# if test -z "$max_task"; then max_task=20; fi
if test -z "$name"; then name=tes; fi
if test -z "$cpu"; then cpu=4; fi
if test -z "$mem"; then mem=4; fi

wait_time=60

set +e

if test -z "$ids"; then

	while true; do


		sub -d$job_id -p$cpu -m$mem -n$name $@ || sub -p$cpu -m$mem -n$name $@ && break

		sleep $wait_time

	done

else


qu_ids(){

ids=$1

depend=$(echo $ids|cut -d: -f1)
idss=$(echo $ids|cut -d: -f2- --output-delimiter=' ')

ids_run=$(qstat -x $idss |perl -ne '/<Job_Id>(.*?)<\/Job_Id/; print "$1\n"')

for i in $ids_run; do
	depend=$depend:$i
done

echo $depend
}

depend=$(echo $ids|cut -d: -f1)

while true; do
	ids=$(qu_ids $ids)
	if test "$ids" = "$depend"; then
		sub -p$cpu -m$mem -n$name $@ && break
	else
		sub -d$ids -p$cpu -m$mem -n$name $@ && break
		
	fi
	sleep 300
	
done

fi
